using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using DocumentCreationSystem.Models;

namespace DocumentCreationSystem.Services
{
    /// <summary>
    /// AI助手工具服务
    /// 提供文件操作、内容分析、智能搜索等功能
    /// </summary>
    public class AgentToolService
    {
        private readonly ILogger<AgentToolService> _logger;

        private readonly EnhancedFileAccessService _enhancedFileService;
        private readonly ICodeIntelligenceService _codeService;
        private readonly IPatchService _patchService;
        private Project? _currentProject;
        private string? _workingDirectory;
        private string? _allowedProjectPath; // 允许访问的项目路径

        public AgentToolService(ILogger<AgentToolService> logger, ICodeIntelligenceService codeIntelligenceService, IPatchService patchService)
        {
            _logger = logger;
            _codeService = codeIntelligenceService;
            _patchService = patchService;
            _enhancedFileService = new EnhancedFileAccessService(_logger as ILogger<EnhancedFileAccessService> ??
                Microsoft.Extensions.Logging.Abstractions.NullLogger<EnhancedFileAccessService>.Instance);
        }

        /// <summary>
        /// 设置当前项目
        /// </summary>
        public void SetCurrentProject(Project? project)
        {
            _currentProject = project;
            // 设置允许访问的项目路径
            _allowedProjectPath = project?.RootPath;
            _logger.LogInformation($"Agent工具服务项目路径已设置为: {_allowedProjectPath ?? "无限制"}");
        }

        /// <summary>
        /// 设置工作目录
        /// </summary>
        public void SetWorkingDirectory(string? directory)
        {
            // 只有当目录在允许的项目路径下时才设置
            if (directory != null && _allowedProjectPath != null)
            {
                var normalizedDirectory = Path.GetFullPath(directory);
                var normalizedAllowedPath = Path.GetFullPath(_allowedProjectPath);

                if (normalizedDirectory.StartsWith(normalizedAllowedPath, StringComparison.OrdinalIgnoreCase))
                {
                    _workingDirectory = directory;
                    _logger.LogInformation($"Agent工具服务工作目录已设置为: {directory}");
                }
                else
                {
                    _logger.LogWarning($"拒绝设置工作目录，路径超出允许范围: {directory}");
                    _workingDirectory = _allowedProjectPath; // 回退到项目根路径
                }
            }
            else
            {
                _workingDirectory = directory;
                _logger.LogInformation($"Agent工具服务工作目录已设置为: {directory ?? "默认"}");
            }
        }

        /// <summary>
        /// 执行工具命令
        /// </summary>
        public async Task<string> ExecuteToolAsync(string toolName, string parameters, CancellationToken cancellationToken = default)
        {
            try
            {
                _logger.LogInformation($"执行工具: {toolName}, 参数: {parameters}");

                return toolName.ToLower() switch
                {
                    // 基础文件操作
                    "read_file" => await ReadFileAsync(parameters),
                    "write_file" => await WriteFileAsync(parameters),
                    "list_files" => await ListFilesAsync(parameters),

                    // 高级检索工具
                    "scan_project_structure" => await ScanProjectStructureAsync(parameters),
                    "get_file_summary" => await GetFileSummaryAsync(parameters),
                    "analyze_file_relationships" => await AnalyzeFileRelationshipsAsync(parameters),
                    "deep_content_search" => await DeepContentSearchAsync(parameters),
                    "get_project_overview" => await GetProjectOverviewAsync(parameters),

                    // 增强文件访问工具 / 代码智能
                    "get_path_info" => await GetPathInfoAsync(parameters),
                    "get_file_content" => await GetFileContentAsync(parameters),
                    "batch_file_info" => await BatchFileInfoAsync(parameters),
                    "search_paths" => await SearchPathsAsync(parameters),
                    "smart_file_access" => await SmartFileAccessAsync(parameters),
                    "analyze_directory_structure" => await AnalyzeDirectoryStructureAsync(parameters),

                    // 代码智能
                    "code_search" => await CodeSearchAsync(parameters),
                    "open_file_range" => await OpenFileRangeAsync(parameters),
                    "get_diagnostics" => await GetDiagnosticsAsync(parameters),
                        "create_patch" => await CreatePatchToolAsync(parameters),
                        "apply_patch_base64" => await ApplyPatchBase64ToolAsync(parameters),
                    "find_references" => await FindReferencesToolAsync(parameters),
                    "rename_symbol_preview" => await RenameSymbolPreviewToolAsync(parameters),
                    "rename_symbol_apply" => await RenameSymbolApplyToolAsync(parameters),

                    _ => $"未知工具: {toolName}"
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"执行工具失败: {toolName}");
                return $"❌ 执行工具失败: {ex.Message}";
            }
        }

        #region 基础文件操作

        /// <summary>
        /// 读取文件内容
        /// </summary>
        private async Task<string> ReadFileAsync(string parameters)
        {
            try
            {
                var filePath = GetFullPath(parameters.Trim());

                if (!File.Exists(filePath))
                {
                    return $"❌ 文件不存在: {parameters}";
                }

                var content = await File.ReadAllTextAsync(filePath);
                return $"📄 **文件内容**\n文件: {Path.GetFileName(filePath)}\n\n{content}";
            }
            catch (Exception ex)
            {
                return $"❌ 读取文件失败: {ex.Message}";
            }
        }

        /// <summary>
        /// 写入文件内容
        /// </summary>
        private async Task<string> WriteFileAsync(string parameters)
        {
            try
            {
                var parts = parameters.Split('|', 2);
                if (parts.Length < 2)
                {
                    return "❌ 参数格式错误，应为: 文件路径|文件内容";
                }

                var filePath = GetFullPath(parts[0].Trim());
                var content = parts[1];

                await File.WriteAllTextAsync(filePath, content);
                return $"✅ 文件写入成功: {Path.GetFileName(filePath)}";
            }
            catch (Exception ex)
            {
                return $"❌ 写入文件失败: {ex.Message}";
            }
        }

        /// <summary>
        /// 列出文件
        /// </summary>
        private async Task<string> ListFilesAsync(string parameters)
        {
            try
            {
                var targetPath = string.IsNullOrEmpty(parameters) ?
                    (_workingDirectory ?? _currentProject?.RootPath ?? Directory.GetCurrentDirectory()) :
                    GetFullPath(parameters.Trim());

                if (string.IsNullOrEmpty(targetPath) || !Directory.Exists(targetPath))
                {
                    return "❌ 无效的目录路径";
                }

                var files = Directory.GetFiles(targetPath, "*.*", SearchOption.TopDirectoryOnly)
                                   .Take(20)
                                   .Select(f => $"📄 {Path.GetFileName(f)}")
                                   .ToList();

                var directories = Directory.GetDirectories(targetPath)
                                          .Take(10)
                                          .Select(d => $"📁 {Path.GetFileName(d)}/")
                                          .ToList();

                var result = new StringBuilder();
                result.AppendLine($"📁 **目录内容** ({targetPath})");
                result.AppendLine();

                if (directories.Any())
                {
                    result.AppendLine("**文件夹:**");
                    result.AppendLine(string.Join("\n", directories));
                    result.AppendLine();
                }

                if (files.Any())
                {
                    result.AppendLine("**文件:**");
                    result.AppendLine(string.Join("\n", files));
                }

                return result.ToString();
            }
            catch (Exception ex)
            {
                return $"❌ 列出文件失败: {ex.Message}";
            }
        }

        #endregion

        #region 高级检索工具

        /// <summary>
        /// 扫描项目结构
        /// </summary>
        private async Task<string> ScanProjectStructureAsync(string parameters)
        {
            try
            {
                var targetPath = string.IsNullOrEmpty(parameters) ?
                    (_workingDirectory ?? _currentProject?.RootPath ?? Directory.GetCurrentDirectory()) :
                    parameters.Trim();

                if (string.IsNullOrEmpty(targetPath) || !Directory.Exists(targetPath))
                {
                    return "❌ 无效的项目路径或项目路径不存在";
                }

                var result = new StringBuilder();
                result.AppendLine($"📁 **项目结构扫描结果**");
                result.AppendLine($"📍 路径: {targetPath}");

                var files = Directory.GetFiles(targetPath, "*.*", SearchOption.AllDirectories);
                var directories = Directory.GetDirectories(targetPath, "*", SearchOption.AllDirectories);

                result.AppendLine($"📊 统计: {files.Length} 个文件, {directories.Length} 个文件夹");
                result.AppendLine();
                result.AppendLine("🌳 **目录结构**:");

                // 显示前20个文件和文件夹
                var allItems = files.Concat(directories).OrderBy(x => x).Take(20);
                foreach (var item in allItems)
                {
                    var relativePath = Path.GetRelativePath(targetPath, item);
                    var icon = Directory.Exists(item) ? "📁" : GetFileIcon(Path.GetExtension(item));
                    result.AppendLine($"  {icon} {relativePath}");
                }

                if (files.Length + directories.Length > 20)
                {
                    result.AppendLine($"  ... 还有 {files.Length + directories.Length - 20} 个项目");
                }

                return result.ToString();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"扫描项目结构失败: {parameters}");
                return $"❌ 扫描项目结构失败: {ex.Message}";
            }
        }

        /// <summary>
        /// 获取文件摘要
        /// </summary>
        private async Task<string> GetFileSummaryAsync(string parameters)
        {
            try
            {
                var filePath = GetFullPath(parameters.Trim());

                if (!File.Exists(filePath))
                {
                    return $"❌ 文件不存在: {parameters}";
                }

                var content = await File.ReadAllTextAsync(filePath);
                var fileInfo = new FileInfo(filePath);
                var lines = content.Split('\n');
                var words = content.Split(new char[] { ' ', '\n', '\r', '\t' }, StringSplitOptions.RemoveEmptyEntries);

                // 生成简单摘要
                var summary = content.Length > 300 ? content.Substring(0, 300) + "..." : content;

                return $"📄 **文件摘要**\n" +
                       $"📍 文件: {Path.GetFileName(filePath)}\n" +
                       $"📊 大小: {fileInfo.Length} 字节, {lines.Length} 行, {words.Length} 词\n" +
                       $"📅 修改时间: {fileInfo.LastWriteTime:yyyy-MM-dd HH:mm:ss}\n\n" +
                       $"📝 **内容预览**:\n{summary}";
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"获取文件摘要失败: {parameters}");
                return $"❌ 获取文件摘要失败: {ex.Message}";
            }
        }

        /// <summary>
        /// 分析文件关系
        /// </summary>
        private async Task<string> AnalyzeFileRelationshipsAsync(string parameters)
        {
            try
            {
                var targetPath = string.IsNullOrEmpty(parameters) ? _currentProject?.RootPath : parameters.Trim();

                if (string.IsNullOrEmpty(targetPath) || !Directory.Exists(targetPath))
                {
                    return "❌ 无效的项目路径";
                }

                var files = Directory.GetFiles(targetPath, "*.txt", SearchOption.AllDirectories)
                           .Concat(Directory.GetFiles(targetPath, "*.md", SearchOption.AllDirectories))
                           .Take(10) // 限制分析文件数量
                           .ToList();

                var result = new StringBuilder();
                result.AppendLine($"🔍 **文件关系分析**");
                result.AppendLine($"📊 分析了 {files.Count} 个文件");
                result.AppendLine();

                // 简单的文件名相似性分析
                var relationships = new List<string>();
                for (int i = 0; i < files.Count; i++)
                {
                    for (int j = i + 1; j < files.Count; j++)
                    {
                        var name1 = Path.GetFileNameWithoutExtension(files[i]).ToLower();
                        var name2 = Path.GetFileNameWithoutExtension(files[j]).ToLower();

                        if (name1.Contains("章") && name2.Contains("章"))
                        {
                            relationships.Add($"🔗 {Path.GetFileName(files[i])} ↔ {Path.GetFileName(files[j])}: 都是章节文件");
                        }
                        else if (name1.Contains(name2) || name2.Contains(name1))
                        {
                            relationships.Add($"🔗 {Path.GetFileName(files[i])} ↔ {Path.GetFileName(files[j])}: 名称相似");
                        }
                    }
                }

                if (relationships.Any())
                {
                    result.AppendLine("**关联关系**:");
                    foreach (var rel in relationships.Take(10))
                    {
                        result.AppendLine(rel);
                    }
                }
                else
                {
                    result.AppendLine("未发现明显的文件关联关系");
                }

                return result.ToString();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"分析文件关系失败: {parameters}");
                return $"❌ 分析文件关系失败: {ex.Message}";
            }
        }

        /// <summary>
        /// 深度内容搜索
        /// </summary>
        private async Task<string> DeepContentSearchAsync(string parameters)
        {
            try
            {
                var parts = parameters.Split('|');
                if (parts.Length < 1)
                {
                    return "❌ 参数格式错误，应为: 搜索关键词|[搜索路径]";
                }

                var keyword = parts[0].Trim();
                var searchPath = parts.Length > 1 ? parts[1].Trim() : _currentProject?.RootPath;

                if (string.IsNullOrEmpty(searchPath) || !Directory.Exists(searchPath))
                {
                    return "❌ 搜索路径无效";
                }

                var results = new List<string>();
                var files = Directory.GetFiles(searchPath, "*.txt", SearchOption.AllDirectories)
                           .Concat(Directory.GetFiles(searchPath, "*.md", SearchOption.AllDirectories))
                           .Take(20) // 限制搜索文件数量
                           .ToList();

                foreach (var file in files)
                {
                    try
                    {
                        var content = await File.ReadAllTextAsync(file);
                        var lines = content.Split('\n');

                        for (int i = 0; i < lines.Length; i++)
                        {
                            if (lines[i].Contains(keyword, StringComparison.OrdinalIgnoreCase))
                            {
                                var context = $"第{i+1}行: {lines[i].Trim()}";
                                results.Add($"📄 **{Path.GetFileName(file)}**: {context}");

                                if (results.Count >= 10) break; // 限制结果数量
                            }
                        }
                    }
                    catch
                    {
                        // 忽略无法读取的文件
                    }

                    if (results.Count >= 10) break;
                }

                return $"🔍 **深度内容搜索结果**\n" +
                       $"🔎 关键词: {keyword}\n" +
                       $"📊 搜索了 {files.Count} 个文件，找到 {results.Count} 个匹配项\n\n" +
                       $"{string.Join("\n", results)}";
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"深度内容搜索失败: {parameters}");
                return $"❌ 深度内容搜索失败: {ex.Message}";
            }
        }

        /// <summary>
        /// 获取项目概览
        /// </summary>
        private async Task<string> GetProjectOverviewAsync(string parameters)
        {
            try
            {
                var targetPath = string.IsNullOrEmpty(parameters) ? _currentProject?.RootPath : parameters.Trim();
                if (string.IsNullOrEmpty(targetPath) || !Directory.Exists(targetPath))
                {
                    return "❌ 无效的项目路径";
                }

                var allFiles = Directory.GetFiles(targetPath, "*.*", SearchOption.AllDirectories);
                var textFiles = allFiles.Where(f =>
                    f.EndsWith(".txt", StringComparison.OrdinalIgnoreCase) ||
                    f.EndsWith(".md", StringComparison.OrdinalIgnoreCase) ||
                    f.EndsWith(".docx", StringComparison.OrdinalIgnoreCase)).ToList();

                var totalSize = allFiles.Sum(f => new FileInfo(f).Length);
                var fileTypes = allFiles.GroupBy(f => Path.GetExtension(f).ToLower())
                    .ToDictionary(g => g.Key, g => g.Count());

                var result = new StringBuilder();
                result.AppendLine("📊 **项目概览**");
                result.AppendLine($"📍 路径: {targetPath}");
                result.AppendLine($"📁 总文件数: {allFiles.Length}");
                result.AppendLine($"📝 文本文件: {textFiles.Count}");
                result.AppendLine($"💾 总大小: {FormatFileSize(totalSize)}");
                result.AppendLine();

                result.AppendLine("📋 **文件类型分布**:");
                foreach (var type in fileTypes.Take(10))
                {
                    result.AppendLine($"• {type.Key}: {type.Value} 个");
                }

                result.AppendLine();
                result.AppendLine("📖 **主要文件**:");
                foreach (var file in textFiles.Take(10))
                {
                    var fileName = Path.GetFileName(file);
                    var fileSize = new FileInfo(file).Length;
                    result.AppendLine($"• {fileName} ({FormatFileSize(fileSize)})");
                }

                return result.ToString();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"获取项目概览失败: {parameters}");
                return $"❌ 获取项目概览失败: {ex.Message}";
            }
        }

        #endregion

        #region 代码智能工具

            /// <summary>
                /// <summary>
                /// 生成补丁：参数 文件路径|新内容Base64
                /// </summary>
                private async Task<string> CreatePatchToolAsync(string parameters)
                {
                    try
                    {
                        var parts = parameters.Split('|');
                        if (parts.Length < 2) return "❌ 参数格式错误，应为: 文件路径|新内容Base64";
                        var filePath = GetFullPath(parts[0].Trim());
                        var base64 = parts[1].Trim();
                        return await _patchService.CreatePatchAsync(filePath, base64);
                    }
                    catch (Exception ex)
                    {
                        _logger.LogError(ex, $"生成补丁失败: {parameters}");
                        return $"❌ 生成补丁失败: {ex.Message}";
                    }
                }

                /// <summary>
                /// 应用补丁：参数 Base64统一diff
                /// </summary>
                private async Task<string> ApplyPatchBase64ToolAsync(string parameters)
                {
                    try
                    {
                        var basePath = _workingDirectory ?? _currentProject?.RootPath ?? Directory.GetCurrentDirectory();
                        var res = await _patchService.ApplyPatchFromBase64Async(parameters.Trim(), basePath);
                        return res;
                    }
                    catch (Exception ex)
                    {
                        _logger.LogError(ex, $"应用补丁失败: {parameters}");
                        return $"❌ 应用补丁失败: {ex.Message}";
                    }
                }

            /// 代码搜索：支持模式 参数格式：query|globPattern|maxResults
            /// 例如：code_search(Serialize|*.cs|20)
            /// </summary>
            private async Task<string> CodeSearchAsync(string parameters)
            {
                try
                {
                    var parts = parameters.Split('|');
                    if (parts.Length == 0 || string.IsNullOrWhiteSpace(parts[0]))
                        return "❌ 参数格式错误，应为: 关键词|[文件匹配模式]|[最大结果数]";

                    var keyword = parts[0].Trim();
                    var pattern = parts.Length > 1 && !string.IsNullOrWhiteSpace(parts[1]) ? parts[1].Trim() : "*.*";
                    var maxResults =  parts.Length > 2 && int.TryParse(parts[2], out var n) ? Math.Max(1, Math.Min(200, n)) : 50;

                    var basePath = _workingDirectory ?? _currentProject?.RootPath ?? Directory.GetCurrentDirectory();
                    if (!Directory.Exists(basePath))
                        return "❌ 无效的搜索路径";

                    var files = Directory.GetFiles(basePath, pattern, SearchOption.AllDirectories);
                    var results = new List<(string file, int lineNo, string line)>();

                    foreach (var file in files)
                    {
                        try
                        {
                            // 仅扫描文本类文件
                            var ext = Path.GetExtension(file).ToLowerInvariant();
                            if (new[] { ".cs", ".ts", ".js", ".json", ".md", ".txt", ".xml", ".yml", ".yaml", ".csproj" }.Contains(ext))
                            {
                                var lines = await File.ReadAllLinesAsync(file);
                                for (int i = 0; i < lines.Length; i++)
                                {
                                    if (lines[i].IndexOf(keyword, StringComparison.OrdinalIgnoreCase) >= 0)
                                    {
                                        results.Add((file, i + 1, lines[i].Trim()));
                                        if (results.Count >= maxResults) break;
                                    }
                                }
                            }
                        }
                        catch
                        {
                            // 忽略不可读文件
                        }
                        if (results.Count >= maxResults) break;
                    }

                    var sb = new StringBuilder();
                    sb.AppendLine("🔎 代码搜索结果");
                    sb.AppendLine($"📍 路径: {basePath}");
                    sb.AppendLine($"🔎 关键词: {keyword}");
                    sb.AppendLine($"🗂️ 模式: {pattern}");
                    sb.AppendLine($"📊 命中: {results.Count}");
                    sb.AppendLine();

                    foreach (var r in results)
                    {
                        var rel = Path.GetRelativePath(basePath, r.file);
                        sb.AppendLine($"• {rel}:{r.lineNo} | {r.line}");
                    }

                    if (results.Count == 0)
                        sb.AppendLine("(未找到匹配项)");

                    return sb.ToString();
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, $"代码搜索失败: {parameters}");
                    return $"❌ 代码搜索失败: {ex.Message}";
                }
            }

            /// <summary>
            /// 打开文件片段 参数：path|startLine|endLine
            /// 例如：open_file_range(DocumentCreationSystem/Services/AgentToolService.cs|1|60)
            /// </summary>
            private async Task<string> OpenFileRangeAsync(string parameters)
            {
                try
                {
                    var parts = parameters.Split('|');
                    if (parts.Length < 3) return "❌ 参数格式错误，应为: 文件路径|起始行|结束行";

                    var filePath = GetFullPath(parts[0].Trim());
                    if (!File.Exists(filePath)) return $"❌ 文件不存在: {parts[0].Trim()}";

                    if (!int.TryParse(parts[1].Trim(), out var start)) return "❌ 起始行必须是整数";
                    if (!int.TryParse(parts[2].Trim(), out var end)) return "❌ 结束行必须是整数";
                    if (start < 1 || end < start) return "❌ 行号范围不合法";

                    var lines = await File.ReadAllLinesAsync(filePath);
                    end = Math.Min(end, lines.Length);

                    var basePath = _workingDirectory ?? _currentProject?.RootPath ?? Directory.GetCurrentDirectory();
                    var rel = Path.GetRelativePath(basePath, filePath);
                    var sb = new StringBuilder();
                    sb.AppendLine("📄 文件片段");
                    sb.AppendLine($"• 文件: {rel}");
                    sb.AppendLine($"• 行号: {start}-{end} / {lines.Length}");
                    sb.AppendLine();

                    for (int i = start; i <= end; i++)
                    {
                        sb.AppendLine($"{i,5}: {lines[i-1]}");
                    }

                    return sb.ToString();
                }
                catch (UnauthorizedAccessException ua)
                {
                    return $"❌ 访问被拒绝: {ua.Message}";
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, $"打开文件片段失败: {parameters}");
                    return $"❌ 打开文件片段失败: {ex.Message}";
                }
            }


            /// <summary>
            /// Roslyn：获取诊断
            /// 参数：可选 projectPath（csproj）
            /// </summary>
            private async Task<string> GetDiagnosticsAsync(string parameters)
            {
                try
                {
                    var projectPath = string.IsNullOrWhiteSpace(parameters) ? null : parameters.Trim();
                    await _codeService.InitializeAsync(projectPath ?? string.Empty);
                    var diags = await _codeService.GetDiagnosticsAsync(projectPath);
                    var sb = new StringBuilder();
                    sb.AppendLine("🩺 项目诊断");
                    foreach (var d in diags.Take(200))
                    {
                        var loc = d.Location;
                        var file = loc.IsInSource ? Path.GetFileName(loc.SourceTree?.FilePath) : "(非源文件)";
                        var span = loc.GetLineSpan();
                        sb.AppendLine($"• [{d.Severity}] {file}:{span.StartLinePosition.Line + 1}:{span.StartLinePosition.Character + 1} {d.Id} {d.GetMessage()}");
                    }
                    if (!diags.Any()) sb.AppendLine("(无警告/错误)");
                    return sb.ToString();
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, $"获取诊断失败: {parameters}");
                    return $"❌ 获取诊断失败: {ex.Message}";
                }
            }

            /// <summary>
            /// Roslyn：查找引用
            /// 参数：file|line|col
            /// </summary>
            private async Task<string> FindReferencesToolAsync(string parameters)
            {
                try
                {
                    var parts = parameters.Split('|');
                    if (parts.Length < 3) return "❌ 参数格式: 文件|行|列";
                    var file = GetFullPath(parts[0].Trim());
                    var line = int.Parse(parts[1]);
                    var col = int.Parse(parts[2]);
                    await _codeService.InitializeAsync(_currentProject?.RootPath ?? string.Empty);
                    var refs = await _codeService.FindReferencesAsync(file, line, col, null);
                    var basePath = _workingDirectory ?? _currentProject?.RootPath ?? Directory.GetCurrentDirectory();
                    var sb = new StringBuilder();
                    sb.AppendLine("🔗 符号引用");
                    foreach (var r in refs.Take(200))
                    {
                        var rel = Path.GetRelativePath(basePath, r.file);
                        sb.AppendLine($"• {rel}:{r.line}:{r.column} | {r.lineText}");
                    }
                    if (!refs.Any()) sb.AppendLine("(未找到引用)");
                    return sb.ToString();
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, $"查找引用失败: {parameters}");
                    return $"❌ 查找引用失败: {ex.Message}";
                }
            }

                /// <summary>
                /// Roslyn：重命名预览（返回统一 diff 文本）
                /// 参数：file|line|col|newName
                /// </summary>
                private async Task<string> RenameSymbolPreviewToolAsync(string parameters)
                {
                    try
                    {
                        var parts = parameters.Split('|');
                        if (parts.Length < 4) return "❌ 参数格式: 文件|行|列|新名称";
                        var file = GetFullPath(parts[0].Trim());
                        var line = int.Parse(parts[1]);
                        var col = int.Parse(parts[2]);
                        var newName = parts[3].Trim();

                        await _codeService.InitializeAsync(_currentProject?.RootPath ?? string.Empty);
                        var diff = await _codeService.RenameSymbolPreviewAsync(file, line, col, newName, null);
                        if (string.IsNullOrWhiteSpace(diff) || diff.Trim() == "(无变更)")
                        {
                            return "(无变更)";
                        }
                        return diff;
                    }
                    catch (Exception ex)
                    {
                        _logger.LogError(ex, $"重命名预览失败: {parameters}");
                        return $"❌ 重命名预览失败: {ex.Message}";
                    }
                }

                /// <summary>
                /// Roslyn：重命名并应用（预览→补丁Base64→应用）
                /// 参数：file|line|col|newName
                /// </summary>
                private async Task<string> RenameSymbolApplyToolAsync(string parameters)
                {
                    try
                    {
                        var parts = parameters.Split('|');
                        if (parts.Length < 4) return "❌ 参数格式: 文件|行|列|新名称";
                        var file = GetFullPath(parts[0].Trim());
                        var line = int.Parse(parts[1]);
                        var col = int.Parse(parts[2]);
                        var newName = parts[3].Trim();

                        await _codeService.InitializeAsync(_currentProject?.RootPath ?? string.Empty);
                        var diff = await _codeService.RenameSymbolPreviewAsync(file, line, col, newName, null);
                        if (string.IsNullOrWhiteSpace(diff) || diff.Trim() == "(无变更)")
                        {
                            return "(无变更)";
                        }

                        var basePath = _workingDirectory ?? _currentProject?.RootPath ?? Directory.GetCurrentDirectory();
                        var base64 = Convert.ToBase64String(Encoding.UTF8.GetBytes(diff));
                        var result = await _patchService.ApplyPatchFromBase64Async(base64, basePath);
                        return result;
                    }
                    catch (Exception ex)
                    {
                        _logger.LogError(ex, $"重命名并应用失败: {parameters}");
                        return $"❌ 重命名并应用失败: {ex.Message}";
                    }
                }

            #region 辅助方法

        /// <summary>
        /// 获取完整路径，并验证是否在允许的项目路径范围内
        /// </summary>
        private string GetFullPath(string path)
        {
            string fullPath;

            if (Path.IsPathRooted(path))
            {
                fullPath = path;
            }
            else
            {
                // 优先使用工作目录，然后是当前项目路径，最后是当前工作目录
                var basePath = _workingDirectory ?? _currentProject?.RootPath ?? Directory.GetCurrentDirectory();
                fullPath = Path.Combine(basePath, path);
            }

            // 验证路径是否在允许的项目路径范围内
            if (_allowedProjectPath != null)
            {
                var normalizedFullPath = Path.GetFullPath(fullPath);
                var normalizedAllowedPath = Path.GetFullPath(_allowedProjectPath);

                if (!normalizedFullPath.StartsWith(normalizedAllowedPath, StringComparison.OrdinalIgnoreCase))
                {
                    _logger.LogWarning($"拒绝访问路径，超出允许范围: {path} -> {normalizedFullPath}");
                    throw new UnauthorizedAccessException($"访问被拒绝：路径超出项目范围 {path}");
                }
            }

            return fullPath;
        }

        /// <summary>
        /// 获取文件图标
        /// </summary>
        private string GetFileIcon(string extension)
        {
            return extension.ToLower() switch
            {
                ".txt" => "📄",
                ".md" => "📝",
                ".docx" => "📘",
                ".pdf" => "📕",
                ".json" => "📋",
                ".xml" => "📄",
                ".html" => "🌐",
                ".css" => "🎨",
                ".js" => "⚡",
                ".cs" => "💻",
                ".py" => "🐍",
                ".jpg" or ".jpeg" or ".png" or ".gif" => "🖼️",
                ".mp3" or ".wav" => "🎵",
                ".mp4" or ".avi" => "🎬",
                _ => "📄"
            };
        }

        /// <summary>
        /// 格式化文件大小
        /// </summary>
        private string FormatFileSize(long bytes)
        {
            string[] sizes = { "B", "KB", "MB", "GB", "TB" };
            double len = bytes;
            int order = 0;
            while (len >= 1024 && order < sizes.Length - 1)
            {
                order++;
                len = len / 1024;
            }
            return $"{len:0.##} {sizes[order]}";
        }

        #endregion

        #region 增强文件访问工具

        /// <summary>
        /// 获取路径信息
        /// </summary>
        private async Task<string> GetPathInfoAsync(string parameters)
        {
            try
            {
                var parts = parameters.Split('|');
                var targetPath = parts.Length > 0 ? parts[0].Trim() : "";
                var includeHidden = parts.Length > 1 && bool.Parse(parts[1].Trim());
                var maxDepth = parts.Length > 2 ? int.Parse(parts[2].Trim()) : 3;

                if (string.IsNullOrEmpty(targetPath))
                {
                    targetPath = _workingDirectory ?? _currentProject?.RootPath ?? Directory.GetCurrentDirectory();
                }

                var result = await _enhancedFileService.GetPathInfoAsync(targetPath, includeHidden, maxDepth);
                return FormatPathInfoResult(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"获取路径信息失败: {parameters}");
                return $"❌ 获取路径信息失败: {ex.Message}";
            }
        }

        /// <summary>
        /// 获取文件内容
        /// </summary>
        private async Task<string> GetFileContentAsync(string parameters)
        {
            try
            {
                var parts = parameters.Split('|');
                var filePath = parts.Length > 0 ? parts[0].Trim() : "";
                var accessMode = parts.Length > 1 ? Enum.Parse<FileAccessMode>(parts[1].Trim(), true) : FileAccessMode.Auto;

                if (string.IsNullOrEmpty(filePath))
                {
                    return "❌ 请指定文件路径";
                }

                var result = await _enhancedFileService.GetFileContentAsync(filePath, accessMode);
                return FormatFileContentResult(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"获取文件内容失败: {parameters}");
                return $"❌ 获取文件内容失败: {ex.Message}";
            }
        }

        /// <summary>
        /// 智能文件访问
        /// </summary>
        private async Task<string> SmartFileAccessAsync(string parameters)
        {
            try
            {
                var filePath = parameters.Trim();
                if (string.IsNullOrEmpty(filePath))
                {
                    return "❌ 请指定文件路径";
                }

                // 智能判断访问策略
                var result = await _enhancedFileService.GetFileContentAsync(filePath, FileAccessMode.Smart);

                var output = new StringBuilder();
                output.AppendLine($"🧠 **智能文件访问结果**");
                output.AppendLine($"📁 文件: {Path.GetFileName(filePath)}");
                output.AppendLine($"📊 策略: {GetAccessStrategyDescription(result.AccessStrategy)}");
                output.AppendLine($"📏 大小: {FormatFileSize(result.FileSize)}");
                output.AppendLine($"🕒 修改: {result.LastModified:yyyy-MM-dd HH:mm:ss}");
                output.AppendLine();

                if (!string.IsNullOrEmpty(result.Content))
                {
                    output.AppendLine("📄 **内容**:");
                    output.AppendLine("```");
                    output.AppendLine(result.Content);
                    output.AppendLine("```");
                }

                if (!string.IsNullOrEmpty(result.ErrorMessage))
                {
                    output.AppendLine($"❌ 错误: {result.ErrorMessage}");
                }

                return output.ToString();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"智能文件访问失败: {parameters}");
                return $"❌ 智能文件访问失败: {ex.Message}";
            }
        }

        /// <summary>
        /// 搜索路径
        /// </summary>
        private async Task<string> SearchPathsAsync(string parameters)
        {
            try
            {
                var parts = parameters.Split('|');
                var basePath = parts.Length > 0 ? parts[0].Trim() : "";
                var searchPattern = parts.Length > 1 ? parts[1].Trim() : "*";
                var recursive = parts.Length > 2 ? bool.Parse(parts[2].Trim()) : true;

                if (string.IsNullOrEmpty(basePath))
                {
                    basePath = _workingDirectory ?? _currentProject?.RootPath ?? Directory.GetCurrentDirectory();
                }

                var searchOptions = new PathSearchOptions
                {
                    Recursive = recursive,
                    IncludeDetailedInfo = true,
                    IncludeContentPreview = false,
                    MaxResults = 50
                };

                var result = await _enhancedFileService.SearchPathsAsync(basePath, searchPattern, searchOptions);
                return FormatPathSearchResult(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"搜索路径失败: {parameters}");
                return $"❌ 搜索路径失败: {ex.Message}";
            }
        }

        /// <summary>
        /// 批量文件信息
        /// </summary>
        private async Task<string> BatchFileInfoAsync(string parameters)
        {
            try
            {
                var parts = parameters.Split('|');
                var pathsParam = parts.Length > 0 ? parts[0].Trim() : "";
                var includeContent = parts.Length > 1 && bool.Parse(parts[1].Trim());

                if (string.IsNullOrEmpty(pathsParam))
                {
                    return "❌ 请指定文件路径列表";
                }

                var filePaths = pathsParam.Split(',').Select(p => p.Trim()).Where(p => !string.IsNullOrEmpty(p));
                var result = await _enhancedFileService.GetBatchFileInfoAsync(filePaths, includeContent);
                return FormatBatchFileInfoResult(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"批量获取文件信息失败: {parameters}");
                return $"❌ 批量获取文件信息失败: {ex.Message}";
            }
        }

        /// <summary>
        /// 分析目录结构
        /// </summary>
        private async Task<string> AnalyzeDirectoryStructureAsync(string parameters)
        {
            try
            {
                var targetPath = string.IsNullOrEmpty(parameters) ?
                    (_workingDirectory ?? _currentProject?.RootPath ?? Directory.GetCurrentDirectory()) :
                    parameters.Trim();

                var result = await _enhancedFileService.GetPathInfoAsync(targetPath, false, 2);

                var output = new StringBuilder();
                output.AppendLine($"🏗️ **目录结构分析**");
                output.AppendLine($"📍 路径: {result.FullPath}");
                output.AppendLine($"📁 目录数: {result.DirectoryCount}");
                output.AppendLine($"📄 文件数: {result.FileCount}");
                output.AppendLine($"💾 总大小: {FormatFileSize(result.TotalSize)}");
                output.AppendLine();

                if (result.FileTypeDistribution?.Any() == true)
                {
                    output.AppendLine("📊 **文件类型分布**:");
                    foreach (var type in result.FileTypeDistribution.OrderByDescending(x => x.Value).Take(10))
                    {
                        output.AppendLine($"• {(string.IsNullOrEmpty(type.Key) ? "无扩展名" : type.Key)}: {type.Value} 个");
                    }
                    output.AppendLine();
                }

                if (result.Children?.Any() == true)
                {
                    output.AppendLine("🌳 **主要内容**:");
                    foreach (var child in result.Children.Take(20))
                    {
                        var icon = child.IsDirectory ? "📁" : GetFileIcon(child.Extension);
                        var sizeInfo = child.IsFile ? $" ({FormatFileSize(child.FileSize)})" : "";
                        output.AppendLine($"  {icon} {child.Name}{sizeInfo}");
                    }
                }

                return output.ToString();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"分析目录结构失败: {parameters}");
                return $"❌ 分析目录结构失败: {ex.Message}";
            }
        }

        #endregion

        #region 格式化方法

        /// <summary>
        /// 格式化路径信息结果
        /// </summary>
        private string FormatPathInfoResult(PathInfoResult result)
        {
            var output = new StringBuilder();

            if (!string.IsNullOrEmpty(result.ErrorMessage))
            {
                return $"❌ {result.ErrorMessage}";
            }

            output.AppendLine($"📍 **路径信息**");
            output.AppendLine($"🔗 完整路径: {result.FullPath}");
            output.AppendLine($"📛 名称: {result.Name}");
            output.AppendLine($"📂 类型: {(result.IsDirectory ? "目录" : "文件")}");

            if (result.IsFile)
            {
                output.AppendLine($"📏 大小: {FormatFileSize(result.FileSize)}");
                output.AppendLine($"📄 扩展名: {result.Extension}");
                output.AppendLine($"📝 文本文件: {(result.IsTextFile ? "是" : "否")}");
            }
            else if (result.IsDirectory)
            {
                output.AppendLine($"📁 子目录: {result.DirectoryCount}");
                output.AppendLine($"📄 文件数: {result.FileCount}");
                output.AppendLine($"💾 总大小: {FormatFileSize(result.TotalSize)}");
            }

            output.AppendLine($"🕒 修改时间: {result.LastModified:yyyy-MM-dd HH:mm:ss}");

            return output.ToString();
        }

        /// <summary>
        /// 格式化文件内容结果
        /// </summary>
        private string FormatFileContentResult(FileContentResult result)
        {
            var output = new StringBuilder();

            if (!string.IsNullOrEmpty(result.ErrorMessage))
            {
                return $"❌ {result.ErrorMessage}";
            }

            output.AppendLine($"📄 **文件内容**");
            output.AppendLine($"📁 文件: {Path.GetFileName(result.FilePath)}");
            output.AppendLine($"📊 策略: {GetAccessStrategyDescription(result.AccessStrategy)}");
            output.AppendLine($"✅ 完整: {(result.IsComplete ? "是" : "否")}");
            output.AppendLine($"📏 大小: {FormatFileSize(result.FileSize)}");

            if (result.TotalLines.HasValue)
            {
                output.AppendLine($"📝 总行数: {result.TotalLines}");
            }

            if (result.PreviewLines.HasValue)
            {
                output.AppendLine($"👀 预览行数: {result.PreviewLines}");
            }

            output.AppendLine();

            if (!string.IsNullOrEmpty(result.Content))
            {
                output.AppendLine("📄 **内容**:");
                output.AppendLine("```");
                output.AppendLine(result.Content);
                output.AppendLine("```");
            }

            return output.ToString();
        }

        /// <summary>
        /// 格式化批量文件信息结果
        /// </summary>
        private string FormatBatchFileInfoResult(BatchFileInfoResult result)
        {
            var output = new StringBuilder();

            output.AppendLine($"📊 **批量文件信息**");
            output.AppendLine($"📄 总文件数: {result.TotalFiles}");
            output.AppendLine($"✅ 有效文件: {result.ValidFiles}");
            output.AppendLine($"📝 文本文件: {result.TextFiles}");
            output.AppendLine($"💾 总大小: {FormatFileSize(result.TotalSize)}");
            output.AppendLine();

            output.AppendLine("📋 **文件列表**:");
            foreach (var file in result.Files.Take(20))
            {
                var icon = file.IsTextFile ? "📄" : "📁";
                var status = file.Exists ? "✅" : "❌";
                var sizeInfo = file.Exists ? $" ({FormatFileSize(file.FileSize)})" : "";
                output.AppendLine($"  {status} {icon} {file.FileName}{sizeInfo}");

                if (!string.IsNullOrEmpty(file.ContentPreview))
                {
                    output.AppendLine($"    💭 预览: {file.ContentPreview.Substring(0, Math.Min(100, file.ContentPreview.Length))}...");
                }
            }

            if (result.Files.Count > 20)
            {
                output.AppendLine($"  ... 还有 {result.Files.Count - 20} 个文件");
            }

            return output.ToString();
        }

        /// <summary>
        /// 格式化路径搜索结果
        /// </summary>
        private string FormatPathSearchResult(PathSearchResult result)
        {
            var output = new StringBuilder();

            if (!string.IsNullOrEmpty(result.ErrorMessage))
            {
                return $"❌ {result.ErrorMessage}";
            }

            output.AppendLine($"🔍 **路径搜索结果**");
            output.AppendLine($"📍 基础路径: {result.BasePath}");
            output.AppendLine($"🔎 搜索模式: {result.SearchPattern}");
            output.AppendLine($"📊 总匹配数: {result.TotalMatches}");
            output.AppendLine($"📄 匹配文件: {result.MatchedFiles.Count}");
            output.AppendLine($"📁 匹配目录: {result.MatchedDirectories.Count}");
            output.AppendLine();

            if (result.MatchedFiles.Any())
            {
                output.AppendLine("📄 **匹配的文件**:");
                foreach (var file in result.MatchedFiles.Take(10))
                {
                    var fileName = Path.GetFileName(file);
                    var relativePath = Path.GetRelativePath(result.BasePath, file);
                    output.AppendLine($"  📄 {fileName} ({relativePath})");
                }

                if (result.MatchedFiles.Count > 10)
                {
                    output.AppendLine($"  ... 还有 {result.MatchedFiles.Count - 10} 个文件");
                }
                output.AppendLine();
            }

            if (result.MatchedDirectories.Any())
            {
                output.AppendLine("📁 **匹配的目录**:");
                foreach (var dir in result.MatchedDirectories.Take(10))
                {
                    var dirName = Path.GetFileName(dir);
                    var relativePath = Path.GetRelativePath(result.BasePath, dir);
                    output.AppendLine($"  📁 {dirName} ({relativePath})");
                }

                if (result.MatchedDirectories.Count > 10)
                {
                    output.AppendLine($"  ... 还有 {result.MatchedDirectories.Count - 10} 个目录");
                }
            }

            return output.ToString();
        }

        /// <summary>
        /// 获取访问策略描述
        /// </summary>
        private string GetAccessStrategyDescription(FileAccessStrategy strategy)
        {
            return strategy switch
            {
                FileAccessStrategy.FullRead => "完整读取",
                FileAccessStrategy.PartialRead => "部分读取",
                FileAccessStrategy.PreviewOnly => "仅预览",
                FileAccessStrategy.SummaryOnly => "仅摘要",
                FileAccessStrategy.MetadataOnly => "仅元数据",
                _ => "未知策略"
            };
        }



        #endregion

	        #endregion

    }
}
